package com.song.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

public class MyRunnable implements Runnable {

    private String userinfo = "";
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    public MyRunnable() {}
    public MyRunnable(String str) {
        jedis.auth("redisroot");
        this.userinfo = str;
    }

    @Override
    public void run() {
        jedis.watch("watchkeys");// watchkeys
        String val = jedis.get("watchkeys");
        int i = Integer.parseInt(val);
        try {
            if (i >= 1 && i <= 10) {  //抢购

                Transaction tx = jedis.multi();
                tx.incrBy("watchkeys", -1);
                List<Object> list = tx.exec(); // 提交事务，如果此时watchkeys被改动了，则返回null  因为有jedis.watch(watchkeys);
                if (list == null || list.size() == 0) {

                    String failuserifo = "fail" + userinfo;
                    String failinfo = "用户：" + failuserifo + "商品争抢失败，抢购失败";
                    System.out.println(failinfo);
                    /* 抢购失败业务逻辑 */
                    jedis.setnx(failuserifo, failinfo);
                } else {
                    for (Object succ : list) {
                        String succuserifo = "succ" + succ.toString() + userinfo;
                        String succinfo = "用户：" + succuserifo + "抢购成功，当前抢购成功人数:"
                                + (1 - (i - 10));
                        System.out.println(succinfo);
                        /* 抢购成功业务逻辑 */
                        jedis.setnx(succuserifo, succinfo);
                    }
                }
            } else {
                String failuserifo = "kcfail" + userinfo;
                String failinfo1 = "用户：" + failuserifo + "商品被抢购完毕，抢购失败";
                System.out.println(failinfo1);
                jedis.setnx(failuserifo, failinfo1);
                // Thread.sleep(500);
                return;
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

}
